package com.ostsm.advmainapplication.Receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.ostms.adv.utils.CommonUtils;
import com.ostms.adv.utils.HttpTools;
import com.ostms.adv.utils.LOG;
import com.ostms.adv.utils.Tools;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.FormBody;

public class PackageReplaceReceiver extends BroadcastReceiver {
    private static final String TAG = PackageReplaceReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("安装包有变化");
        if (intent.getAction().equals("android.intent.action.PACKAGE_REPLACED")) {
            LOG.i("PackageReplaceReceiver.onReceive", "包替换监听启动");
            if ("package:com.ostms.adv".equals(intent.getDataString())) {
                sendupdateStatus(context);
            }
        }
        // 接收安装广播
        if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) {
            String packageName = intent.getDataString();
            System.out.println("安装了:" + packageName + "包名的程序");
        }

        //接收卸载广播
        if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")) {
            String packageName = intent.getDataString();
            System.out.println("卸载了:" + packageName + "包名的程序");
        }
    }

    public static final String STATUSCODESUCCESS = "1";
    public static final String STATUSCODEFAILUR = "4";

    private void sendupdateStatus(Context context) {
        String planId = Tools.getProperties(context, CommonUtils.PLAN_ID_SETTING);
        LOG.i(TAG, "应用重装planId==>" + planId);
        if (planId == null)
            return;
        Tools.setProperties(context, CommonUtils.PLAN_ID_SETTING, null);
        String path = CommonUtils.STATUSCHANGE;
        FormBody.Builder builder = Tools.getOkHttpFormBodyBuilder(context);
        builder.add(CommonUtils.PLAN_ID, planId);
        builder.add(CommonUtils.STATUSCODE, STATUSCODESUCCESS);

        new HttpTools(context).sendPostdata(path, builder, new HttpTools.HttpLisenner() {
            @Override
            public void onFailure(Call call, IOException e) {
                LOG.i(TAG, "更新计划状态失败:" + e);
            }

            @Override
            public void onResponse(Call call, String result) {
                LOG.i(TAG, "更新计划状态成功");
            }
        });
    }
}
